<script setup lang="ts">
import { useEffect } from "@/framework/vue/hooks";
import { ref, shallowRef } from "vue";

/* 元素可见性监听 */

defineOptions({ name: "visible-observer" });

const element = shallowRef<HTMLDivElement>();
const visible = ref(false);

useEffect(() => {
  const el = element.value;
  if (!el) return;

  const observer = new IntersectionObserver(entries => {
    const entry = entries[entries.length - 1];
    visible.value = entry.isIntersecting;
  });
  observer.observe(el);
  return () => {
    observer.unobserve(el);
    observer.disconnect();
  };
});
</script>

<template>
  <div ref="element" class="visible-observer">
    <slot :visible="visible" />
  </div>
</template>

<style lang="less">
.visible-observer {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
</style>
